﻿

namespace TwlAction
{
    using System;
    using System.Collections.Generic;
    using Config;
    using TwlPhy;

    public class BaseAction
    {
        public ActionData actionData;
        public int spawnFrame;//出生时间
        protected ActionConfig actionCfg;

        public virtual string resName
        {
            get;
            protected set;
        }
        public virtual DymicBox3D box3d
        {
            get;
            protected set;
        }

        protected BaseEntity roleAgent
        {
            get
            {
                return EntityMgr.getRole<BaseEntity>(actionData.ownerId);
            }
        }

        /// <summary>
        /// 创建
        /// </summary>
        internal void onCreate()
        {
            spawnFrame = FrameMgr.NowFrame;
            readActionConfig();
            createBox();
            createDisplay();
            onSpawn();
        }

        protected virtual void readActionConfig()
        {
            actionCfg = ActionConfig.get(actionData.actionId);
        }

        protected virtual void createBox()
        {
            BaseEntity role = roleAgent;
            if (role == null)
            {
                onDeath();
            }
            else
            {
            }
        }

        /// <summary>
        /// 创建展示
        /// </summary>
        protected virtual void createDisplay()
        {

        }

        /// <summary>
        /// 子类重写创建
        /// </summary>
        public virtual void onSpawn()
        {

        }

        /// <summary>
        /// 基础技能tick 技能可能有以下事件
        /// 播动画
        /// 播特效
        /// 播音效
        /// 伤害检测
        /// 做位移
        /// </summary>
        public virtual void Tick()
        {
            if (FrameMgr.NowFrame - this.spawnFrame >= actionCfg.maxFrame)
            {
                this.onDeath();
                return;
            }
            int index = FrameMgr.NowFrame - spawnFrame;
            checkAction(index, 1, actionCfg.damageFrame);
            checkAction(index, 2, actionCfg.moveFrame);
            checkAction(index, 3, actionCfg.animFrame);
            checkAction(index, 4, actionCfg.effectFrame);
            checkAction(index, 5, actionCfg.audioFrame);                      
        }

        protected virtual void checkAction(int index, int actionType, Dictionary<int, int> keyFrame)
        {
            if (keyFrame != null)
            {
                int cfgId = -1;
                if (keyFrame.TryGetValue(index, out cfgId))
                {
                    ActionMgr.Instance.playAction(actionType, this.actionData, cfgId);
                }
            }
        }

        public virtual void onDeath()
        {
            ActionMgr.Instance.remove(this.actionData);
        }

        public virtual void onDispose()
        {            
            actionData = null;
        }

   

    }
}
